import { getApi } from '@/requestConfig';
import { authorizeRenewOSS } from '@/services/api/api-aliyun';
import { getToken } from '@/utils/token';
import { getUUID } from '@/utils/uuid';
import { CoffeeOutlined, DeleteOutlined, FileWordOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import moment from 'moment';
import { useEffect } from 'react';
import { useModel } from 'umi';
const OSS = require('ali-oss');

interface TextEditorProps {
  extra?: React.ReactNode;
  defaultContent?: string | undefined;
  readonly: boolean;
  value?: string;
  onInit?: (editor: any) => void;
  onChange?: (value: string) => void;
  onClick?: (value: any) => void;
  tinyID: string;
}

const TextEditor: React.FC<TextEditorProps> = ({
  extra,
  defaultContent,
  readonly,
  onInit,
  value,
  onChange,
  onClick,
  tinyID
}) => {
  const { initialState, setInitialState } = useModel('@@initialState');

  useEffect(() => {
    tinyMCE.init({
      selector: '#' + tinyID,
      height: 633,
      resize: true,
      language: 'zh_CN',
      readonly: readonly,
      plugins:
        'tpImportword tpIndent2em tpLayout  axupimgs directionality table fullscreen preview print quickbars wordcount',
      menubar: false,
      toolbar:
        // preview print wordcount
        'tpImportword tpIndent2em tpLayout | undo redo | alignleft aligncenter alignright alignjustify |  |  fullscreen',
      statusbar: true,
      //statusbar 左下角
      elementpath: false,
      contextmenu: 'table',
      placeholder: '请输入...',
      //快速栏插入工具栏
      quickbars_selection_toolbar: false,
      quickbars_insert_toolbar: false,
      //图片对话框中上报标签开关
      image_advtab: false,
      image_uploadtab: true,
      visual_anchor_class: '',
      automatic_uploads: true,
      resize_img_proportional: false,
      // images_upload_handler: function (blobInfo: any, succFun: any, failFun: any, progress: any) {
      //   //     console.log('====', succFun, failFun, progress);
      //   //     const img = 'data:image/jpeg;base64,' + blobInfo.base64();
      //   //  succFun(img);
      //   // failFun('失败了');
      //   return new Promise((resolve, reject) => {
      //     // failFun('失败了');
      //     console.log('===============',  blobInfo.base64());
      //     const img = blobInfo.base64();
      //     succFun(img);

      //     // const  file = blobInfo.blob();
      //     // if (!file.name)
      //     //   file.name = 'vue-' + Date.now() + Math.floor(Math.random() * 1000) + '.png';
      //     //   const  DOMURL = window.URL || window.webkitURL || window;
      //     // succFun(DOMURL.createObjectURL(file));
      //   });
      // },
      images_upload_handler: function (blobInfo: any, succFun: any, failFun: any, progress: any) {
        return new Promise((resolve, reject) => {
          authorizeRenewOSS({
            type: 12,
          }).then((response) => {
            if (response.code == 0) {
              const headers = {
                'Content-Disposition': 'attachment;',
              };

              const multipartUploadOptions = {
                callback: {
                  url: `${getApi()}/product12/upload`,
                  body: response.data.callbackBody,
                  contentType: response.data.callbackContentType,
                  satoken: getToken(),
                },
                progress: (index: number, cpt: any, res: any) => {
                  progress(Math.round(index * 100).toFixed(2));
                },
                headers,
              };
              const OSSData = {
                accessKeyId: response.data.accessKeyId,
                accessKeySecret: response.data.accessKeySecret,
                stsToken: response.data.securityToken,
                region: response.data.callbackRegion,
                bucket: response.data.callbackBucket,
              };

              const client = new OSS({
                region: OSSData.region,
                accessKeyId: OSSData.accessKeyId,
                accessKeySecret: OSSData.accessKeySecret,
                stsToken: OSSData.stsToken,
                refreshSTSToken: async () => {
                  const response = await authorizeRenewOSS();
                  return {
                    accessKeyId: response.data.accessKeyId,
                    accessKeySecret: response.data.accessKeySecret,
                    stsToken: response.data.securityToken,
                  };
                },
                refreshSTSTokenInterval: 300000,
                bucket: OSSData.bucket,
              });

              client
                .multipartUpload(
                  `${initialState?.currentUser?.organizationName
                  }/nrsh/senior/image/${moment().format('YYYY-MM-DD')}/${getUUID()}.png`,
                  new Blob([blobInfo.blob()]),
                  multipartUploadOptions,
                )
                .then((response: any) => {
                  if (response.data.code == 0) {
                    resolve(response.data.data);
                  } else {
                    failFun('上传失败');
                  }
                })
                .catch((e: any) => {
                  failFun('上传失败');
                });
            }
          });
        }).then((url) => {
          succFun(url);
        });
      },
      content_css: 'default',
      content_style:
        'body {font-family:Helvetica,Arial,sans-serif;font-size:14px }.read-write-plain-text-only {-webkit-user-modify:read-write-plaintext-only;}.split-row-select-active {background-color:#e6f7ff }.word-mark-error-major {border-bottom:3px solid rgba(255, 195, 0, 1);cursor:pointer;}.word-mark-error-critical {border-bottom:3px solid rgba(255, 87, 51, 1);cursor:pointer;}.word-mark-error-blocker {border-bottom:3px solid rgba(199, 0, 57, 1);cursor:pointer;}.word-mark-error-highlight-major {background-color:rgba(255, 195, 0, 0.5);border-bottom:3px solid rgba(255, 195, 0, 1);cursor:pointer;}.word-mark-error-highlight-critical {background-color:rgba(255, 87, 51, 0.5);border-bottom:3px solid rgba(255, 87, 51, 1);cursor:pointer;}.word-mark-error-highlight-blocker {background-color:rgba(199, 0, 57, 0.5);border-bottom:3px solid rgba(199, 0, 57, 1);cursor:pointer;}.word-mark-right {color:rgb(255,255,255);background-color:rgb(13,188,121);cursor:pointer;}.word-mark-right:hover {color:rgb(255,255,255);}.word-mark-right-highlight {color:rgb(255,255,255);font-size:30px;background-color:rgb(41,155,73);cursor:pointer;}.word-mark-right-highlight:hover {color:rgb(255,255,255);}',
      setup(editor: any) {
        editor.on('init', (e: any) => { });
        editor.on('input', (e: any) => {
          onChange!(tinyMCE.EditorManager.get(tinyID).getContent());
        });
        editor.on('change', (e: any) => {
          onChange!(tinyMCE.EditorManager.get(tinyID).getContent());
          console.log('======', tinyMCE.EditorManager.get(tinyID).getContent());
        });
        editor.on('click', (e: any) => {
          onClick!(e);
        });
      },
      init_instance_callback: (editor: any) => {
        onInit!(editor);
        editor.setContent('');
        if (defaultContent) {
          editor.insertContent(defaultContent);
          onChange!(editor.getContent());
        } else if (value) {

          editor.insertContent(value);
        }

        editor.shortcuts.remove('Ctrl+Y');
        editor.shortcuts.remove('Command+Y');
        editor.shortcuts.remove('Ctrl+Shift+Z');
        editor.shortcuts.remove('Command+Shift+Z');

        tinyMCE.EditorManager.add(editor);
      },
    });

    return () => {
      tinyMCE.EditorManager.get(tinyID).destroy();
    };
  }, []);




  return (
    <>
      <div style={{ display: 'flex' }}>
        <Button
          disabled={readonly}
          type="primary"
          icon={<FileWordOutlined />}
          key="check"
          size="small"
          style={{
            marginBottom: 10,
          }}
          onClick={() => {
            tinyMCE.EditorManager.get(tinyID).execCommand('mceTpImportword');
          }}
        >
          导入Word文档（.docx）
        </Button>
        <div style={{ display: 'flex' }}>

          {extra}
          <Button
            icon={<DeleteOutlined />}
            // style={{ position: 'absolute', right: 0 }}
            key="clear"
            size="small"
            danger
            onClick={() => {
              tinyMCE.EditorManager.get(tinyID).setContent('');
              message.success('清空成功');
            }}
          >
            清空
          </Button>
        </div>
      </div>

      <textarea id={tinyID} />
    </>
  );
};

export default TextEditor;
